package mensa.upb;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class XmlReader {
	public static void read(InputStream in) {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp;
		try {
			sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			XmlContentHandler ach = new XmlContentHandler();
			xr.setContentHandler(ach);
			xr.parse(changeEncoding(in, "windows-1252", "utf-8"));
		} catch (ParserConfigurationException e) {
		} catch (SAXException e) {
		} catch (IOException e) {
		}
	}

	public static void read2(FileInputStream in) {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp;
		try {
			sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			XmlContentHandler ach = new XmlContentHandler();
			xr.setContentHandler(ach);
			xr.parse(changeEncoding(in, "windows-1252", "utf-8"));
		} catch (ParserConfigurationException e) {
		} catch (SAXException e) {
		} catch (IOException e) {
		}
	}

	private static InputSource changeEncoding(InputStream in, String from,
			String to) {
		String f = from.toLowerCase();
		String t = to.toLowerCase();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(in, f));
			StringBuilder sb = new StringBuilder();
			String l = br.readLine().toLowerCase().replace(f, t);
			sb.append(l + "\n");
			while ((l = br.readLine()) != null) {
				sb.append(l);
			}
			br.close();
			return new InputSource(new StringReader(sb.toString()));
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}
		return null;
	}
}
